package com.example.shop.common.config;

import com.example.shop.common.convert.LocalDateConverter;
import com.example.shop.common.convert.LocalDateTimeConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;



@Configuration
public class SpringMvcExtendsConfig implements WebMvcConfigurer {


    private final StringHttpMessageConverter stringHttpMessageConverter;
    @Resource(name = "commonObjectMapper")
    private ObjectMapper objectMapper;
    private final LocalDateConverter localDateConverter;
    private final LocalDateTimeConverter localDateTimeConverter;

    public SpringMvcExtendsConfig(StringHttpMessageConverter stringHttpMessageConverter, LocalDateConverter localDateConverter, LocalDateTimeConverter localDateTimeConverter) {
        this.stringHttpMessageConverter = stringHttpMessageConverter;
        this.localDateConverter = localDateConverter;
        this.localDateTimeConverter = localDateTimeConverter;
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
        mappingJackson2HttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
        return mappingJackson2HttpMessageConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        stringHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        stringHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(localDateConverter);
        registry.addConverter(localDateTimeConverter);
    }
}
